<?php

namespace brand\logic;

use app\admin\model\AuthRule;
use brand\Brand;
use brand\build\Columns;
use brand\page\Table;
use brand\tools\Functions;
use brand\tools\Random;
use think\Exception;

class CurdBuild
{

    public static function tableColumns()
    {

        $columns['table'] = Brand::Builder('表名')->form_props(['readonly' => true])->build();
        $columns['title'] = Brand::Builder('名称')->form_props(['readonly' => true])->build();
        $columns['engine'] = Brand::Builder('引擎')->form_props(['readonly' => true])->build();
        $columns['rows'] = Brand::Builder('行数')->form_props(['readonly' => true])->build();
        $columns['files'] = Brand::Builder('行数')->form(false)->table_action_type('button')
            ->build_button('文件设置','el-icon-edit')
            ->button_desc('控制器/模型/验证/语言包等文件')
            ->button_url(url('curd/files',request()->get())->build())
            ->button_data(['table','title'])
            ->build();


        Table::$right_buttons = [];

        //CURD设置
        Table::$custom_button[] = Brand::Builder()->build_button('字段设置','el-icon-setting')
            ->button_visible('is_curd')
            ->button_url(url('tableFields',request()->get())->build())
            ->button_data(['table'])
            ->build();

        //CURD设置
        Table::$custom_button[] = Brand::Builder()->build_button('页面设置','el-icon-setting')
            ->button_visible('is_curd')
            ->button_url(url('pageConfig',request()->get())->build())
            ->button_data(['table'])
            ->build();

        //同步字段
        Table::$custom_button[]  = Brand::Builder()->build_button('同步字段','el-icon-refresh-right','confirm')
            ->button_confirm('保持表字段与CURD配置字段同步，现有的CURD字段不受影响')
            ->button_data(['table'])
            ->button_url(url('syncTableCurd',request()->get())->build())
            ->button_visible('is_curd')
            ->build();

        Columns::setConfig($columns);

    }

    public static function tableFieldsColumns()
    {
        $columns['field'] = Brand::Builder('字段名')->form(false)->build();
        $columns['title'] = Brand::Builder('名称')->form(false)->build();
        $columns['curd'] = Brand::Builder('表单属性')->form(false)->build();
        return $columns;
    }

    public static function tableFieldsValues($db_table)
    {
        $db_table = BrandHelper::addonGetPrefix($db_table);
        $fields = Database::getTableFields($db_table);
        //配置信息
        $curdConfig = BrandHelper::getCurdConfigByName($db_table);
        $brandList = Config::getBrandList();
        $res = [];
        foreach ($fields as $field) {
            $comment = Database::curdComment($field['comment']);
            if (!isset($curdConfig['columns'][$field['name']])){
                $method = '未设置';
                $curd_set = 0;
            }else{
                $method = Functions::toCamelCase( ($curdConfig['columns'][$field['name']]['form']['method'] ?? "input") );
                $curd_set = 1;
            }
            $res[] = [
                'field' => $field['name'],
                'title' => $comment['title'] ?: $field['name'],
                'curd' => $brandList[$method] ?? $method,
                'curd_set' => $curd_set
            ];
        }
        return $res;
    }

    /**
     * 表字段生成CURD
     * @param $field
     * @param $table
     */
    public static function fieldToCurd($title,$field, $table,$addon = null)
    {

        $tableConfig = BrandHelper::getCurdConfigByName($table);
        if (!$tableConfig) return _error('请先生成Curd文件');

        $row_table = $table;
        if ($addon){
            $table_prefix = get_addon_info($addon,'table_prefix');
            if ($table_prefix) $row_table = $table_prefix . $table;
        }
        $db_fields = Database::getTableFields($row_table);

        $table_field = "";
        foreach ($db_fields as $db_field) {
            if ( $db_field['name'] == $field){
                $table_field = $db_field;
            }
        }

        $comment_info = Database::curdComment($table_field['comment']);
        $column = Database::curdMethodByName($table_field , $comment_info['method'] ?? "");
        $column['title'] = $title;
        $tableConfig['columns'][$field] = $column;

        //写入信息
        self::setCurdFile($table,'columns',$tableConfig['columns']);
    }

    public static function filesForm($table,$addon = null)
    {


        $curdConf = BrandHelper::getCurdConfigByName($table);
        $set_file = [];

        $curd = Config::$curd_path.($table).Config::CURD_SUFFIX;


        if (isset($curdConf['model']['namespace'])){
            $model = str_replace('\\','/',$curdConf['model']['namespace']).'/'.Functions::toCamelCase($table).'.php';
        }else{
            $model = Config::$model_path .Functions::toCamelCase($table).'.php';
        }

        if (isset($curdConf['controller']['namespace'])){
            $controller = (str_replace('\\','/',$curdConf['controller']['namespace'])).'/'.Functions::toCamelCase($table).'.php';
        }else{
            $set_file[] = 'controller';
            $controller = Config::$controller_path .Functions::toCamelCase($table).'.php';
        }

        if (isset($curdConf['validate']['validateNamespace'])){
            $validate = str_replace('\\','/',$curdConf['validate']['validateNamespace']).'/'.Functions::toCamelCase($table).'.php';
        }else{
            $validate = Config::$validate_path .Functions::toCamelCase($table).'.php';
        }

        if (!$curdConf){
            $set_file[] = 'curd';
        }

        $files = [
            'controller'    =>  $controller,
            'model'         =>  $model,
            'validate'      =>  $validate,
            'curd'          =>  $curd,
            'set_file'      =>  $set_file,
            'menu'          =>  false,
            'cover'         =>  false
        ];

        //设置生成的文件
        $set_file = [
            ['label' => 'CURD文件','value' => 'curd'],
            ['label' => '控制器','value' => 'controller'],
            ['label' => '模型','value' => 'model'],
            ['label' => '验证器','value' => 'validate'],
        ];



        $noFile = '<span style="color: red">上述路径文件已存在，若强制修改，将覆盖上述文件。</span>';
        $existsFile = '<span style="color: green">文件不存在，将在相应路径生成文件。若自定义文件，请先确认文件是否存在。</span>';

        $columns['curd'] = Brand::Builder('CURD文件')->form_validate([['required' => true]])
            ->form_marker('<span>CURD文件名与表名保存一致。<span><br>'. ( BrandHelper::FileExistsException ($curd) ? $noFile: $existsFile))
            ->form_props(['readonly'=>true])
            ->build();
        $columns['model'] = Brand::Builder('模型')->form_validate([['required' => true]])
            ->form_marker(  BrandHelper::FileExistsException($model) ? $noFile: $existsFile)
            ->build();
        $columns['controller'] = Brand::Builder('控制器')->form_validate([['required' => true]])
            ->form_marker('控制器路径必须在：'. Config::$controller_path.'文件夹下。<br>' . ( BrandHelper::FileExistsException ($controller) ? $noFile: $existsFile))
            ->build();
        $columns['validate'] = Brand::Builder('验证器')
            ->form_marker(   BrandHelper::FileExistsException($validate) ? $noFile: $existsFile)
            ->build();
        $columns['set_file'] = Brand::Builder('生成文件','checkbox')
            ->form_options($set_file)
            ->form_marker( ' CURD：生成的文件可自动完成增删改查，可设置联表查询等操作，生成文件之后，可单独设置CURD功能，<a href="" target="_blank" style="color: red">点击了解详情></a>')
            ->build();
        $columns['cover'] = Brand::Builder('强制覆盖','switcher')->form_validate([['required' => true]])
            ->form_marker( '<span style="color: red">强制覆盖开启将覆盖原有文件，请谨慎操作</span>')
            ->build();
        $columns['menu'] = Brand::Builder('生成菜单','switcher')
            ->form_marker( '默认生成增删改查权限和菜单')
            ->build();

        return [$columns,$files];
    }


    public static function getTableData()
    {
        $tableList = Database::tablesInfo();

        foreach ($tableList as $key => $table) {
            $curdPath = BrandHelper::getCurdTablesPath() . $table['table'] . Config::CURD_SUFFIX;
            $tableList[$key]['is_curd'] = file_exists($curdPath) ? 1 : 0;
            if (!$table['title']) $tableList[$key]['title'] = $table['table'];
        }
        return $tableList;
    }

    public static function setCurdFile($curdName, $field, $value)
    {
        $curdName = BrandHelper::addonTableName($curdName);
        $conf = BrandHelper::getCurdConfigByName($curdName);
        if ($conf){
            //备份
            if (Config::CURD_IS_BACKUPS){
                $backupsPath = root_path() . Config::$CURD_BACKUPS_PATH . $curdName .'__'. date('Y_m_d_H_i_s') .'__'. Random::build() . Config::CURD_SUFFIX;
                file_put_contents($backupsPath,Functions::jsonFormat($conf));
            }
        }
        $curdPath = BrandHelper::getCurdTablesPath() . $curdName . Config::CURD_SUFFIX;
        $curd = BrandHelper::getCurdConfigByName($curdName);

        if ($field == 'columns'){
            $value = self::saveColumnsCheck($value);
        }

        $curd[$field]  =   $value;
        //写入信息
        file_put_contents($curdPath,Functions::jsonFormat($curd));
    }

    public static function saveColumnsCheck($columns)
    {
        //地区
        $area_level = 0;
        $area_index = '';
        $area_config = [];

        foreach ($columns as $key => $column) {
            if (isset($column['special_type'])){

                switch ( $column['special_type'] ){
                    case 'province':
                    case 'province_id':
                        $area_level = max($area_level, 1);
                        $area_index = $area_index ?: $key;
                        $area_config['province'] = $key;
                        $area_config['type'] = 'area';
                        break;
                    case 'city':
                    case 'city_id':
                        $area_level = max($area_level, 2);
                        $area_index = $area_index ?: $key;
                        $area_config['city'] = $key;
                        $area_config['type'] = 'area';
                        break;
                    case 'area':
                    case 'area_id':
                        $area_level = max($area_level, 3);
                        $area_index = $area_index ?: $key;
                        $area_config['area'] = $key;
                        $area_config['type'] = 'area';
                        break;
                    default:
                        break;
                }

            }
        }
        if ($area_level > 0){
            $area_config['area_level'] = $area_level;
            $area = Brand::Builder('地区')
                ->method_cascader()
                ->form('cascader',$area_config)
                ->field('special_action','area')
                ->table(false)
                ->search('=')
                ->build();
            $columns = BrandHelper::columnsInsertArray($columns,$area_index,['brand_admin_area' => $area]);
        }

        return $columns;

    }
    /**
     * 构建curl文件
     * @param $table
     * @param $title
     * @param $params
     */
    public static function makeFileCurd($table, $title, $params)
    {
        $file = $params['curd'] ?? "";
        $cover = $params['cover'] ?? 0;

        //文件是否存在
        if (file_exists(root_path().$file) && !$cover){
            return ;
        }

        //获取字段详情
        $fields = Database::getTableFields($table);
        //获取表格详情
        $table_columns = Database::fieldsToColumns($fields);

        //构建关联字段
        $table_columns = Database::buildRelevancy($table_columns);

        //获取页面设置
        $page = Database::buildPageByTable($table,$fields);

        //插件信息
        $addon = BrandHelper::addonInfo();

        //写入文件
        self::setCurdFile($table , 'columns' , $table_columns);
        self::setCurdFile($table , 'title' , $title);
        self::setCurdFile($table , 'page' , $page);
        if ($addon){
            self::setCurdFile($table , 'addon' , $addon);
        }
    }

    public static function makeFileModel($table,$title,$params,$row_table = null)
    {
        //CURD文件是否存在
        $curdPath = root_path().($params['curd'] ?? '');
        if (!file_exists($curdPath) ){
            throw new \Exception('生成文件必须选择CURD');
        }
        $file = $params['model'] ?? "";
        $cover = $params['cover'] ?? 0;
        $pathInfo = BrandHelper::pathInfo($file);
        $curdPathInfo = BrandHelper::pathInfo($curdPath);
        //文件是否存在
        if (file_exists(root_path().$file) && $cover != 1){
            return ;
        }
        //路径是否存在
        BrandHelper::IsDir($pathInfo['namespace'],1);


        //软删除
        $SoftDeleteNameSpace = $SoftDelete = '';
        $confData = [];
        //数据字段信息
        $fields = Database::getTableFields($row_table);
        foreach ($fields as $field) {
            if ($field['key'] == 'PRI' && $field['name'] != 'id'){
                $confData['pk'] = $field['name'];
            }
            if ($field['name'] == Config::DELETE_TIME){
                $SoftDeleteNameSpace = 'use think\model\concern\SoftDelete;';
                $SoftDelete = 'use SoftDelete;';
            }
        }
        if (!isset($confData['pk']) || !$confData['pk']) $confData['pk'] = "id";

        //配置信息
        $confData = array_merge(
            [
                'namespace'=>$pathInfo['namespace'] ?? "",
                'tableComment' => $title,
                'modelName'=>$pathInfo['className'] ?? "",
                'curdName'  =>  $curdPathInfo['className'] ?? "",
                'tableName'  =>  $row_table,
                'SoftDeleteNameSpace'  =>  $SoftDeleteNameSpace,
                'SoftDelete'  =>  $SoftDelete,
            ],
            $confData
        );
        //生成文件
        $pathName = root_path().$file;
        self::writeToFile('model',$confData,$pathName);
        $confData['fileName'] = $pathInfo['className'] . '.php';
        $confData['pathName'] = $file;
        //写入文件
        self::setCurdFile($table , 'model' , $confData);
    }

    public static function makeFileController($table, $title, $params)
    {
        //CURD文件是否存在
        $curdPath = root_path().($params['curd'] ?? '');
        if (!file_exists($curdPath) ){
            throw new \Exception('生成文件必须选择CURD');
        }

        $file = $params['controller'] ?? "";
        $cover = $params['cover'] ?? 0;


        $pathInfo = BrandHelper::pathInfo($file);

        //文件是否存在
        if (file_exists(root_path().$file) && $cover != 1){
            return ;
        }
        //路径是否存在
        BrandHelper::IsDir($pathInfo['namespace'],1);

        //数据字段信息
        $fields = Database::getTableFields($table);
        $tablePk = "";
        foreach ($fields as $field) {
            if ($field['key'] == 'PRI'){
                $tablePk = $field['name'];
            }
        }


        //配置信息
        $confData = [
            'namespace'=>$pathInfo['namespace'] ?? "",
            'tableComment' => $title,
            'controllerName'=>$pathInfo['className'] ?? "",
            'curdName'=>$table,
            'pk'=>$tablePk,
        ];

        //生成文件
        $pathName = root_path().$file;
        self::writeToFile('controller',$confData,$pathName);
        $confData['fileName'] = $pathInfo['className'] . '.php';
        $confData['pathName'] = $file;
        $confData['pk'] = $tablePk;
        //写入文件
        self::setCurdFile($table , 'controller' , $confData);
    }

    public static function makeFileValidate($table, $title, $params,$row_table)
    {
        //CURD文件是否存在
        $curdPath = root_path().($params['curd'] ?? '');
        if (!file_exists($curdPath) ){
            throw new \Exception('生成文件必须选择CURD');
        }

        $file = $params['validate'] ?? "";
        $cover = $params['cover'] ?? 0;
        //文件是否存在
        if (file_exists(root_path().$file) && $cover != 1){
            return ;
        }
        $pathInfo = BrandHelper::pathInfo($file);
        //路径是否存在
        BrandHelper::IsDir($pathInfo['namespace'],1);
        //数据字段信息
        $fields = Database::getTableFields($row_table);
        $rule = $message = $field_info = "";
        foreach ($fields as $field) {
            if ($field['key'] == 'PRI'){
                continue;
            }
            if ($field['is_null'] == 'NO'){
                $rule .= "'{$field['name']}' => 'require', ";
                $comment = Database::curdComment($field['comment'],$field['name']);
                $field_info .= "'{$field['name']}' => '{$comment['title']}', ";
            }
        }
        //配置信息
        $confData = [
            'validateNamespace'=>$pathInfo['namespace'] ?? "",
            'validateName'=>$pathInfo['className'] ?? "",
            'rule'  =>  $rule,
            'message'  =>  $message,
            'field'  =>  $field_info,
        ];

        //生成文件
        $pathName = root_path().$file;
        self::writeToFile('validate',$confData,$pathName);
        //写入文件
        self::setCurdFile($table , 'validate' , $confData);
    }

    public static function makeMenu($table, $title, $params , $addon = null)
    {

        $Auth = new AuthRule();
        $curd = BrandHelper::getCurdConfigByName($table);
        $controller = $curd['controller'] ?? [];
        if (!isset($controller['namespace']) || !$controller['namespace']){
            $controller_file  = $params['controller'] ?? "";
            $pathInfo = BrandHelper::pathInfo($controller_file);
            $namespace = $pathInfo['namespace'] ?? "";
        }else{
            $namespace = $controller['namespace'].'\\';
        }

        $path = str_replace(str_replace('/','\\',Config::$controller_path)  , '',$namespace);
        if ($path){
            $path =  str_replace('/','.',$path) . '.'.$table;
        }else{
            $path = $table;
        }
        $pid = 1;
        if ($addon){
            $addon_info = get_addon_info($addon);
            $path = "/" . $addon_info['name'] . "/" . ($addon_info['admin'] ?? 'admin') . "/" .$path;
            $pid = $Auth->where('name',$addon_info['name'])->value('id') ?: $pid;
        }

        //列表
        $save['name'] = $path;
        $save['title'] = $title;
        if ($Auth->where($save)->find()) return;
        $save['pid'] = $pid;
        $save['ismenu'] = 1;
        $save['status'] = 'normal';
        $pid = $Auth->insertGetId($save);

        $sonAuth = [
            ['pid' => $pid,'title'=>'新增','name'=>$path.'/add','status'=>'normal'],
            ['pid' => $pid,'title'=>'编辑','name'=>$path.'/edit','status'=>'normal'],
            ['pid' => $pid,'title'=>'删除','name'=>$path.'/del','status'=>'normal'],
        ];
        $Auth->saveAll($sonAuth);
    }


    /**
     * 写入模版到文件
     * @param string $name
     * @param array  $data
     * @param string $pathname
     * @return mixed
     */
    protected static function writeToFile($name, $data, $pathname)
    {
        foreach ($data as $index => &$datum) {
            $datum = is_array($datum) ? '' : $datum;
        }
        unset($datum);
        $content = self::getReplacedStub($name, $data);

        if (!is_dir(dirname($pathname))) {
            mkdir(dirname($pathname), 0755, true);
        }
        return file_put_contents($pathname, $content);
    }

    /**
     * 获取替换后的数据
     * @param string $name
     * @param array  $data
     * @return string
     */
    protected static function getReplacedStub($name, $data)
    {
        foreach ($data as $index => &$datum) {
            $datum = is_array($datum) ? '' : $datum;
        }
        unset($datum);
        $search = $replace = [];
        foreach ($data as $k => $v) {
            $search[] = "{%{$k}%}";
            $replace[] = $v;
        }
        $stubname = self::getStub($name);
        $stub = file_get_contents($stubname);
        $content = str_replace($search, $replace, $stub);
        return $content;
    }

    /**
     * 获取基础模板
     * @param string $name
     * @return string
     */
    protected static function getStub($name)
    {
        return root_path() . Config::STUB_PATH . $name . Config::STUB_SUFFIX;
    }

    public static function syncTableCurd($table)
    {
        $curdConf = BrandHelper::getCurdConfigByName($table);

        $fields = Database::getTableFields($table);

        $columns = $curdColumns = $curdConf['columns'] ?? [];

        //数据库有curd没有
        foreach ($fields as $field) {
            if (!isset($curdColumns[$field['name']])){
                $comment = Database::curdComment($field['comment'],$field['name']);
                $column = Database::curdMethodByName($field , $comment['method'] ?? "");
                $column['title'] = $comment['title'];
                $curdColumns[$field['name']] = $column;
            }
            if (isset($columns[$field['name']])) unset($columns[$field['name']]);
        }

        //curd有数据库没有
        foreach ($columns as $field => $column) {
            unset($curdColumns[$field]);
        }

        $tableInfo = Database::tablesInfo($table)[0] ?? [];
        $title = $tableInfo['title'] ?? $table;
        if ($title != $curdConf['title']){
            //同步标题
            self::setCurdFile($table,'title',$title);
        }

        //同步行
        self::setCurdFile($table,'columns',$curdColumns);
    }

    /**
     * 编辑CURD表单属性
     * @param $table
     * @param $field
     */
    public static function editFieldCurdForm($table,$field)
    {

        //此表配置
        $tableConfig = BrandHelper::getCurdConfigByName($table);
        $tableConfigValue = $tableConfig['columns'][$field] ?? [];


        //此表方法
        $tableMethod = Functions::toCamelCase($tableConfigValue['form']['method'] ?? 'input');

        //标题
        $columns['title'] = Brand::Builder('标题')->form_validate([['required' => true]])->build();
        $raws['title'] = $tableConfigValue['title'];

        //备注

        $raws['marker'] = $tableConfigValue['form']['marker'] ?? "";

        //类型
        $brandList = Config::getBrandList();
        $brandOptions = BrandHelper::formatOptions($brandList);
        $columns['curd_method'] = Brand::Builder('类型','select')->form_options($brandOptions)->form_marker( '<span style="color: red">修改类型时，请注意数据库格式！！！</span>' )->build();
        $raws['curd_method'] = $tableMethod;


        $raws['special_type'] = $tableConfigValue['special_type'] ?? "";

        //循环支持的所有表单
        foreach ($brandList as $brandMethod => $brandLabel) {
            $ClassName = Config::BRAND_NAMESPACE . Functions::toCamelCase($brandMethod);
            if (class_exists($ClassName)){

                $ClassObject = new $ClassName();
                $methodConfig = $ClassObject->buildConfigColumn($tableConfigValue,'curd_method');

                $columns[$brandMethod] = $methodConfig['column'];
                $raws[$brandMethod] = $methodConfig['value'];

            }
        }




        //是否自动写入时间
        $auto_times['no'] = '不自动写入';
        $auto_times['create_time'] = '创建时自动写入';
        $auto_times['update_time'] = '更新时自动写入';
        $auto_times['delete_time'] = '删除时自动写入（软删除 配合模型使用）';
        $columns['auto_time'] = [
            'form'  =>  [
                'method'    =>  'select',
                'options' =>BrandHelper::formatOptions($auto_times),
                'visible'   =>  [
                    ['prop' => 'curd_method', 'value' => 'Date']
                ],
                'marker'    =>  '自动写入的字段不会在表单显示。<span style="color:red;">软删除依赖模型，可在控制器中使用方法db_reset()方法引入模型</span>'
            ],
            'title' =>  '自动写入时间'
        ];

        $auto_time = 'no';
        if (isset($tableConfigValue['form']['create_time']) && $tableConfigValue['form']['create_time']){
            $auto_time = 'create_time';
        }
        if (isset($tableConfigValue['form']['update_time']) && $tableConfigValue['form']['update_time']){
            $auto_time = 'update_time';
        }
        if (isset($tableConfigValue['form']['delete_time']) && $tableConfigValue['form']['delete_time']){
            $auto_time = 'delete_time';
        }


        $raws['auto_time'] = $auto_time;



        //搜索
        $tableCondition = $tableConfigValue['search']['condition'] ?? 0;
        $raws['search'] = $tableCondition;


        //表单是否显示
        $raws['form_show'] = (isset($tableConfigValue['form']['status']) && $tableConfigValue['form']['status'] == false) ? 0 : 1;

        //是否必填项 默认不必填
        $validate_required = 0;
        $validate = $tableConfigValue['form']['validate'] ?? [];
        foreach ($validate as $item) {
            if (isset($item['required']) && $item['required']){
                $validate_required = 1;
            }
        }
        $raws['validate_required'] = $validate_required;

        //表格是否显示
        $raws['table_show'] = (isset($tableConfigValue['table']['status']) && $tableConfigValue['table']['status'] == false) ? 0 : 1;
        $raws['show_type'] = $tableConfigValue['table']['show_type'] ?? "";

        //表单是否排序
        $raws['table_order'] = (isset($tableConfigValue['table']['props']['sortable']) && $tableConfigValue['table']['props']['sortable'] !== false) ? 1 : 0;

        //表格宽度
        $raws['table_width'] = $tableConfigValue['table']['props']['width'] ?? '';

        //select是否多选
        $raws['select_multiple'] = (isset($tableConfigValue['form']['props']['multiple']) && $tableConfigValue['form']['props']['multiple']) ? 1 : 0;

        //排序
        $column_keys = array_keys($tableConfig['columns']);
        $sort['__ba__top'] = '顶部';
        $sort_parent = $column_keys[array_search($field,$column_keys) - 1] ?? 0;
        foreach ($tableConfig['columns'] as $key => $column) {
            if ($key == $field || isset($column['form']['is_relevancy']) && $column['form']['is_relevancy']) continue;
            $sort[$key] = $column['title'];
        }
        $raws['sort'] = $sort_parent;
        //表格Props
        $props_options['value'] = \brand\Brand::Builder('键')->build();
        $props_options['label'] = \brand\Brand::Builder('描述')->build();


        //追加props
        $raws['form_append_props'] = BrandHelper::formatOptions($tableConfigValue['form']['append_props'] ?? []);
        $raws['table_append_props'] = BrandHelper::formatOptions($tableConfigValue['table']['append_props'] ?? []);

        $tabs['表单'] = [
            'form_show' => Brand::Builder('显示','radio')->form_options(BrandHelper::formatOptions(['不显示','显示']))->build(),
            'validate_required' => Brand::Builder('必填','radio')->form_options(BrandHelper::formatOptions(['非必填项','必填项']))->build(),
            'marker' => Brand::Builder('提示信息')->form_marker("<span style='color: green'>提示信息会显示在表单下方，支持html代码</span>")->build(),
            'select_multiple' => Brand::Builder('多选','radio')->form_visible([['prop' => 'curd_method', 'value' => 'Select']])->form_options(BrandHelper::formatOptions(['单选','多选']))->build(),
            //特殊字符
            'special_type' => Brand::Builder('特殊字符')->method_select()->form_options(BrandHelper::formatOptions(array_merge(['无'],Config::SPECIAL_TYPE)))->build(),
            'form_append_props' => Brand::Builder('自定义Props','arrays')
                ->form_options([$props_options])
                ->form_marker('只能自定义非系统生成的props,参考： <a href="https://element.eleme.cn/#/zh-CN/component/form#form-attributes" target="_blank">点击查看</a> ')
                ->form_props([
                    'append'    =>  true,
                    'span'  =>  12,
                    'title' => false
                ])
                ->build(),
        ];
        $tabs['表格'] = [
            'show_type' => Brand::Builder('显示类型','select')->form_options(BrandHelper::formatOptions(Config::TABLE_SHOW_TYPE))->build(),
            'table_show' => Brand::Builder('显示','radio')->form_options(BrandHelper::formatOptions(['不显示','显示']))->build(),
            'table_order' => Brand::Builder('排序','radio')->form_options(BrandHelper::formatOptions(['不排序','排序']))->build(),
            'table_width' => Brand::Builder('宽度','number')->build(),
            'table_append_props' => Brand::Builder('自定义Props','arrays')
                ->form_options([$props_options])
                ->form_marker('只能自定义非系统生成的props,参考： <a href="https://element.eleme.cn/#/zh-CN/component/table#table-attributes" target="_blank">点击查看</a> ')
                ->form_props([
                    'append'    =>  true,
                    'span'  =>  12,
                    'title' => false
                ])
                ->build(),
        ];
        $tabs['搜索'] = [
            'search' => Brand::Builder('搜索','select')->form_options(BrandHelper::formatOptions(Config::getConditionList()))->build(),
        ];
        $tabs['其它'] = [
            'sort' => Brand::Builder('排序','select')->form_marker('排在此字段下')->form_options(BrandHelper::formatOptions($sort))->build(),
        ];
        $columns['setting'] = Brand::Builder('','tabs')->form(['tabs_options'=>$tabs,'tabs_values'=>$raws])->build();


        return [$columns,$raws];
    }


    public static function submitFieldCurdConf($field, $table)
    {
        //此表配置
        $tableConfig = BrandHelper::getCurdConfigByName($table);
        //此字段配置
        $fieldConfig = $tableConfig['columns'][$field] ?? [];
        if (!$fieldConfig) throw new \Exception('配置错误');

        $curd_method = request()->param('curd_method');

        $params['param'] = request()->param($curd_method,[]);
        $params['title'] = request()->param('title','');
        $params['validate_required'] = request()->param('validate_required',0);
        $params['search'] = request()->param('search','=');
        $params['field'] = $field;
        $params['table_show'] = request()->param('table_show',1);
        $params['table_order'] = request()->param('table_order',0);
        $params['form_show'] = request()->param('form_show',1);
        $params['curd_method'] = $curd_method;
        $params['marker'] = request()->param('marker',"");
        $params['auto_time'] = request()->param('auto_time',"no");
        $params['form_append_props'] = request()->param('form_append_props',[]);
        $params['table_append_props'] = request()->param('table_append_props',[]);
        $params['special_type'] = request()->param('special_type',"");
        $params['show_type'] = request()->param('show_type',"");
        $params['sort'] = request()->param('sort',-1);
        $params['table_width'] = request()->param('table_width','');

        $table_columns = $tableConfig['columns'];
        $ClassName = Config::BRAND_NAMESPACE . Functions::toCamelCase($curd_method);
        if (class_exists($ClassName)){

            $ClassObject = new $ClassName();
            $table_columns = $ClassObject->paramsToCurdConf($params,$fieldConfig,$tableConfig['columns']);

        }
        //构建关联字段
        $table_columns = Database::buildRelevancy($table_columns);
        self::setCurdFile($table,'columns',$table_columns);
    }

    public static function getPageConfigColumns($table)
    {
        $fields = [];
        foreach ( (Database::getTableFields($table) ?? []) as $field) {
            $comment = Database::curdComment($field['comment']);
            $fields[$field['name']] = $field['name'] .' - '. ($comment['title'] ?? '');
        }


        $columns['pk'] = Brand::Builder('主键')->method_select()
            ->form_options(BrandHelper::formatOptions($fields))
            ->build();
        $columns['title'] = Brand::Builder('标题')->build();
        $columns['describe'] = Brand::Builder('小标题')->build();
        $header_buttons = [];
        foreach ( Table::$header_buttons as $item) {
            $header_buttons[$item] = Config::buttonName($item);
        }
        $columns['header_buttons'] = Brand::Builder('默认顶部按钮','checkbox')->form_options(BrandHelper::formatOptions($header_buttons))->build();

        $right_buttons = [];
        foreach ( Table::$right_buttons as $item) {
            $right_buttons[$item] = Config::buttonName($item);
        }
        $columns['right_buttons'] = Brand::Builder('默认顶部按钮','checkbox')->form_options(BrandHelper::formatOptions($right_buttons))->build();



        $columns['statistics'] = Brand::Builder('统计字段')->method_select()->form_props(["multiple"=>true])
            ->form_options(BrandHelper::formatOptions($fields))
            ->build();

        $custom_buttons['icon'] = Brand::Builder('图标')->form_marker('<a target="_blank" href="https://element.eleme.cn/#/zh-CN/component/icon">图标地址</a>')->build();
        $custom_buttons['title'] = Brand::Builder('名称')->build();
        $custom_buttons['event'] = Brand::Builder('按钮事件')->method_select()->form_options(BrandHelper::formatOptions(Config::$button_event))->build();
        $custom_buttons['url'] = Brand::Builder('URL地址')->form_marker(request()->root() . '后面的链接')->build();
        $custom_buttons['confirm'] = Brand::Builder('提示文字')->form_visible([['prop' => 'event', 'value' => 'confirm']])->build();



        $columns['custom_header_buttons'] = Brand::Builder('设置顶部按钮','arrays')
            ->form_options([$custom_buttons])
            ->form_props( [
                'append'    =>  true
            ])
            ->build();
        $custom_buttons['visible'] = Brand::Builder('验证字段')->form_marker('值为true才显示当前按钮')->form_options(BrandHelper::formatOptions(Config::$button_event))->build();
        $custom_buttons['confirm'] = Brand::Builder('提示文字')->form_marker('表格中的值可用{xxx}代替，如： 确定删除{username}吗？ username为表格数据字段名')->form_visible([['prop' => 'event', 'value' => 'confirm']])->build();

        $button_data['key'] = Brand::Builder('键')->build();
        $button_data['value'] = Brand::Builder('值')->form_marker('为空则设置为列表值')->build();
        $custom_buttons['data'] = Brand::Builder('参数','arrays')
            ->form_options([$button_data])
            ->form_props( [
                'append'    =>  true,
                'span'  =>  12,
            ])
            ->build();


        $columns['custom_right_buttons'] = Brand::Builder('设置列表按钮','arrays')
            ->form_options([$custom_buttons])
            ->form_props( [
                'append'    =>  true
            ])
            ->build();

        $columns['page_size'] = Brand::Builder('分页','number')->build();


        return $columns;
    }

    public static function getPageConfigValues($table)
    {
        $curd = BrandHelper::getCurdConfigByName($table);
        $page = $curd['page'] ?? [];
        if (!isset($page['title'])) $page['title'] = "";
        if (!isset($page['describe'])) $page['describe'] = "";
        if (!isset($page['header_buttons'])) $page['header_buttons'] = Config::$header_buttons;
        if (!isset($page['right_buttons'])) $page['right_buttons'] = Config::$right_buttons;
        if (!isset($page['page_size'])) $page['page_size'] = Config::$page_size;
        if (!isset($page['custom_header_buttons'])) $page['custom_header_buttons'] = [];
        if (!isset($page['custom_right_buttons'])) $page['custom_right_buttons'] = [];
        return $page;
    }

    public static function setPageConfig($table, $config)
    {
        $table = BrandHelper::addonTableName($table);
        if (!isset($config['table']) || !$config['table']){
            $config['table'] = BrandHelper::addonGetPrefix($table);
        }

        self::setCurdFile($table,'page',$config);
    }

}